package com.dao.impl;

// default package

import static org.hibernate.criterion.Example.create;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.dao.ProanswerDao;
import com.model.Proanswer;
import com.util.Pagination;

/**
 * A data access object (DAO) providing persistence and search support for Proanswer entities. Transaction control of the save(), update() and delete() operations can directly
 * support Spring container-managed transactions or they can be augmented to handle user-managed Spring transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .Proanswer
 * @author MyEclipse Persistence Tools
 */
@Repository("ProanswerDao")
public class ProanswerDaoImpl implements ProanswerDao {
    @Resource
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void save(Proanswer transientInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();

            session.save(transientInstance);

        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public void delete(Proanswer persistentInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();

            session.delete(persistentInstance);

        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Proanswer findById(java.lang.Integer id) {
        try {
            Session session = sessionFactory.getCurrentSession();

            Proanswer instance = (Proanswer) session.get("com.model.Proanswer", id);

            return instance;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Pagination StuScore(Proanswer proanswer, Pagination paperPage) {
        if (proanswer.getPaper().getPapername() == null) {
            proanswer.getPaper().setPapername("");
        }
        if (proanswer.getUser().getUsername() == null) {
            proanswer.getUser().setUsername("");
        }

        String hql = "select p.paper.id, p.paper.papername,p.user.username,p.user.realname,p.user.college,p.user.stunum,sum(p.score),p.user.id from Proanswer p where p.paper.papername like '%" + proanswer.getPaper().getPapername() + "%' and p.user.username like '%"
                + proanswer.getUser().getUsername() + "%' ";

        if (proanswer.getPaper().getId() != null) {
            hql = hql + "and p.paper.id = " + proanswer.getPaper().getId();
        }
        hql = hql + " group by p.paper.id, p.user.id";

        try {
            Session session = sessionFactory.getCurrentSession();
            Query q = session.createQuery(hql);
            paperPage.setTotal(q.list().size());
            paperPage.setTotalpagecountByhand();

            q.setFirstResult((paperPage.getCurrentpage() - 1) * paperPage.getPagesize());
            q.setMaxResults(30);
            paperPage.setList(q.list());
            return paperPage;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    // String hql =
    // "select p.paper.id, p.paper.papername,p.user.username,sum(p.score),p.user.id from Proanswer p where 1=1 group by p.paper.id, p.user.id";

    @Override
    public List findAll() {
        try {
            Session session = sessionFactory.getCurrentSession();

            String queryString = "from Proanswer";
            Query queryObject = session.createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Proanswer merge(Proanswer detachedInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();

            Proanswer result = (Proanswer) session.merge(detachedInstance);

            return result;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public List<Proanswer> getProanswerList(Proanswer proanswer, Pagination page) {
        Session session = sessionFactory.getCurrentSession();

        List<Proanswer> results = session.createCriteria("com.model.Proanswer").add(create(proanswer)).setFirstResult((page.getCurrentpage() - 1) * page.getPagesize() - 1).setMaxResults(page.getPagesize()).list();

        return results;
    }

    @Override
    public List paerInfo(int uid, int pid, String flag) {
        Session session = sessionFactory.getCurrentSession();
        String hql;
        if (flag.equals("yes")) {
            hql = "select pro.programming.title ,pro.programming.score, pro.programming.content, pro.programming.inputdescribe, pro.programming.outputdescribe, pro.programming.inputsample, pro.programming.outputsample,"
                    + "pro.programming.runtimeforjava, pro.programming.memoryforjava, pro.programming.runtime, pro.programming.memoryforc, " + "pro.answer,pro.score  from ClazzProanswer pro where pro.student.id = " + uid + " and pro.paper.id=" + pid;
        } else {
            hql = "select pro.programming.title ,pro.programming.score, pro.programming.content, pro.programming.inputdescribe, pro.programming.outputdescribe, pro.programming.inputsample, pro.programming.outputsample,"
                    + "pro.programming.runtimeforjava, pro.programming.memoryforjava, pro.programming.runtime, pro.programming.memoryforc, " + "pro.answer,pro.score  from Proanswer pro where pro.user.id = " + uid + " and pro.paper.id=" + pid;
        }

        Query q = session.createQuery(hql);
        return q.list();
    }

    @Override
    public List<?> showRank() {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Paper p where p.rank = 1 ORDER BY p.begintime desc ";
        Query query = session.createQuery(hql);
        return query.list();
    }

    @Override
    public List rankInfo(int id) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "select pro.user , sum(pro.score) ,max(pro.submittime)  from  Proanswer pro where pro.paper.id = " + id + " GROUP BY pro.user.id order by sum(pro.score) desc,max(pro.submittime) asc";
        Query query = session.createQuery(hql);
        return query.list();
    }

    @Override
    public List<?> showDifficulty() {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Paper p ORDER BY p.begintime desc ";
        Query query = session.createQuery(hql);
        return query.list();
    }

    @Override
    public List difficultyInfo(int id) {
        String sql = "select pro.programid , count(*)  ,sum(pro.score!=0)  from  db_proanswer pro where pro.paperid = " + id + " GROUP BY pro.programid ORDER BY sum(pro.score!=0)/sum(pro.score!=0 or pro.score=0) desc";
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createSQLQuery(sql);

        return query.list();
    }

}